package com.ilearn.spring.future.service;

import com.ilearn.spring.future.dto.IEvent;
import com.ilearn.spring.future.entity.User;
import com.ilearn.spring.future.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;

import javax.servlet.http.HttpServletResponse;

/**
 * @Project: cmcchq
 * @Description:
 * @Version 1.0
 * @Throws :
 * @Author: <li>2019/6/26 lyndon Create 1.0
 * @Copyright (c)2019-2019 版权所有
 * @Modified By:
 */
@Slf4j
//@Service
public class UserService {


    public User getUser(Integer id, String threadName, String reqId) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return User.builder()
                .id(id)
                .name("Sync")
                .threadName(threadName)
                .reqId(reqId)
                .build();
    }

    @Async
    public void getAsyncUser(IEvent iEvent, Integer id, String threadName, String reqId) {
        //public void getAsyncUser(Integer id, String threadName, String reqId) {
        //IEvent iEvent = ThreadLocalContext.threadLocalIEvent.get();
        //ThreadLocalContext.threadLocalIEvent.remove();
        System.out.println("---------------");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        User asyncUser = User.builder()
                .id(id)
                .name("Async")
                .threadName(threadName)
                .reqId(reqId)
                .build();
        HttpServletResponse response = (HttpServletResponse) iEvent.getResponse();
        ResponseUtil.convertToHttp(response, asyncUser);
        iEvent.complete();
        log.info("Thread {} complete! ReqId is {}", threadName, reqId);
    }

}
